/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.benimetum.beans;
import com.benimetum.items.*;
import com.benimetum.mail.MailSender;
import com.benimetum.managers.*;
import java.io.*;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.model.*;
/**
 *
 * @author anil_inal
 */

@ManagedBean(name="CommunityBean")
@SessionScoped
public class CommunityBean implements Serializable{
    private Community target;
    private String communityName;
    private String firstAnnouncement;       //CommunityBean'deki acıklama grubun ilk announcement'ı olacak 
    private String text;
    private Date date;
    private String header;
    private Community[] memberCommuniy;
    private Community[] adminCommunity;
    private ScheduleModel eventModel;

    public CommunityBean() {
        adminCommunity = CommunityManager.getCommunitysByAdminId(LoginManager.getUser().getId());
         if(LoginManager.isTeacher()){
             memberCommuniy = CommunityManager.getTeachersCommunitys(LoginManager.getUser().getId());
         }
         else{
            memberCommuniy = CommunityManager.getStudentsCommunitys(LoginManager.getUser().getId());
         }
    }

    public void setEventModel(ScheduleModel eventModel) {
        this.eventModel = eventModel;
    }

    public ScheduleModel getEventModel() {
        Event[] studentsEvents = AnnouncementManager.getCommunityEvents(target.getId());
	  eventModel=new DefaultScheduleModel();
	  for (int i = 0; i < studentsEvents.length; i++) {
		Event e = studentsEvents[i];
		DefaultScheduleEvent ev = new DefaultScheduleEvent(e.getText(),e.getDate(), e.getDate());
		ev.setId(e.getId());
		eventModel.addEvent(ev);
	  }
        return eventModel;
    }
    
    

    public void setHeader(String header) {
        this.header = header;
    }

    public String getHeader() {
        return header;
    }

    public Date getDate() {
        return date;
    }

    public void setMemberCommuniy(Community[] memberCommuniy) {
        this.memberCommuniy = memberCommuniy;
    }

    public Community[] getMemberCommuniy() {
        return memberCommuniy;
    }

    public void setAdminCommunity(Community[] adminCommunity) {
        this.adminCommunity = adminCommunity;
    }

    public Community[] getAdminCommunity() {
        return adminCommunity;
    }

    public void setDate(Date date) {
        this.date = date;
    }
    
    
    public String getText() {
        return text;
    }

    public void setText(String Text) {
        this.text = Text;
    }
    
    public Community getTarget() {
	  return target;
    }
    public void setTarget(Community target) {
	  this.target = target;
    }
    public String getCommunityName(){
          return communityName;
    }
    public void setCommunityName(String communityName){
          this.communityName = communityName;
    }
    public String getFirstAnnouncement(){
          return firstAnnouncement;
    }
    public void setFirstAnnouncement(String firstAnnouncement){
          this.firstAnnouncement = firstAnnouncement;
    }
    public void createCommunity(){
          CommunityManager.create(LoginManager.getUser().getId(), communityName);
         adminCommunity = CommunityManager.getCommunitysByAdminId(LoginManager.getUser().getId());
         if(LoginManager.isTeacher()){
             memberCommuniy = CommunityManager.getTeachersCommunitys(LoginManager.getUser().getId());
         }
         else{
            memberCommuniy = CommunityManager.getStudentsCommunitys(LoginManager.getUser().getId());
         }
    }
    
    
    public Community[] giveAll(){
        return CommunityManager.getAllCommunities();
        
    }
    public void joinCommunity()
    {
        CommunityManager.addMember(target.getId(), LoginManager.getUser().getId());
        if(LoginManager.isTeacher()){
             memberCommuniy = CommunityManager.getTeachersCommunitys(LoginManager.getUser().getId());
         }
         else{
            memberCommuniy = CommunityManager.getStudentsCommunitys(LoginManager.getUser().getId());
         }
    }
    
//    public void DesEkle(){
//     try {
//            PrintWriter outputStream = new PrintWriter(new FileOutputStream("description.txt", true));
//            outputStream.println(target.getId()+"="+firstAnnouncement );
//            outputStream.close();
//        } catch (FileNotFoundException ex) {
//            Logger.getLogger(CommunityBean.class.getName()).log(Level.SEVERE, null, ex);
//        }
//    }
//     
    
    public void addGroupAnnouncement(){
	  AnnouncementManager.createCommunityAnnouncement(text+"<br>"+new Date().toLocaleString(), target.getMembers(), target.getAdmin().getId(), target.getId());
	  FacesContext context = FacesContext.getCurrentInstance();
	  HomePageBean obj = context.getApplication().evaluateExpressionGet(context, "#{HomePageBean}", HomePageBean.class);
	  obj.makeBoxFalse();
	  try {
		FacesContext.getCurrentInstance().getExternalContext().redirect("index.xhtml");
	  } catch (IOException ex) {
		Logger.getLogger(CourseBean.class.getName()).log(Level.SEVERE, null, ex);
	  }
    }
    public void addGroupEvent(){
	  AnnouncementManager.createCommunityEvent(text, date, target.getMembers(), target.getAdmin().getId(), target.getId());
	  FacesContext context = FacesContext.getCurrentInstance();
	  HomePageBean obj = context.getApplication().evaluateExpressionGet(context, "#{HomePageBean}", HomePageBean.class);
	  obj.makeBoxFalse();
	  try {
		FacesContext.getCurrentInstance().getExternalContext().redirect("index.xhtml");
	  } catch (IOException ex) {
		Logger.getLogger(CourseBean.class.getName()).log(Level.SEVERE, null, ex);
	  }
    }
    
   public void sendGroupMail(){
       Person[] member = target.getMembers();
	  String[] email=new String[member.length];
	  for (int i = 0; i < member.length; i++) {
		email[i]=member[i].getEmail();
		
	  }
	  MailSender obj=new MailSender(email, "BenimEtum", header, text);
	  Thread thread=new Thread(obj);
	  thread.start();
	  FacesContext context = FacesContext.getCurrentInstance();
	  HomePageBean bean = context.getApplication().evaluateExpressionGet(context, "#{HomePageBean}", HomePageBean.class);
	  bean.makeBoxFalse();
	  try {
		FacesContext.getCurrentInstance().getExternalContext().redirect("index.xhtml");
	  } catch (IOException ex) {
		Logger.getLogger(CourseBean.class.getName()).log(Level.SEVERE, null, ex);
	  }
      }
   public void deleteGroup(){
        CommunityManager.deleteCommunity(target.getId());
    }      
   public void leaveGroup(){
       CommunityManager.deleteMember(target.getId(), LoginManager.getUser().getId());
   }
   public Announcement[] communityAnnouncement(){
       return AnnouncementManager.getCommunityAnnouncements(target.getId());
   }
   public boolean communityAdmin(){
       return target.getAdmin().getId().equals(LoginManager.getUser().getId());
   }
   public boolean checkTarget(){
	  return target!=null;
    }
   
  public boolean memberOf(Community comm){
      return CommunityManager.isMemberOf(LoginManager.getUser().getId(), comm.getId());
  }
  
  public boolean isMemberOf(){
      return CommunityManager.isMemberOf(LoginManager.getUser().getId(), target.getId());
  }
  
  public boolean userType(Person person){
      return person.isTeacher();
  }
}
